package com.liang.shiro;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.liang.pojo.Root;
import com.liang.service.RootService;

public class RootRealm extends AuthorizingRealm{
	@Autowired
	RootService rootService;
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = principals.getPrimaryPrincipal().toString();
		Set<String> roles = rootService.selectRoleByUsername(username);
		Set<String> permissions = rootService.selectPremissionByUsername(username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(roles);
		info.setStringPermissions(permissions);
		return info;
	}

	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = token.getPrincipal().toString();
		Root root = rootService.selectRootByUsername(username);
		if(root==null) {
			return null;
		}else {
	        ByteSource salt = ByteSource.Util.bytes(username);
	        //封装用户信息，构建AuthenticationInfo对象并返回
	        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, root.getPassword(),
	                salt,this.getName());
	        return authcInfo;
		}
	}
}
